package consul
import (
	consulapi "github.com/hashicorp/consul/api"
	"log"
	"strconv"
	"gintest/until"
	"gintest/core/config"
)
var (
	 chost string//cul地址
	 cport int//cul端口
)
type ServiceInfo struct{
	Host string
	Port int
}
var (
	client *consulapi.Client
	err error
)
func Init(){
	chost=config.Sconfig.Read("consul","host")
	cport,_=strconv.Atoi(config.Sconfig.Read("consul","port"))
	// 创建连接consul服务配置
	config := consulapi.DefaultConfig()
	config.Address = chost + ":" + strconv.Itoa(cport)
	client, err = consulapi.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}
}
func Register(tag string,shost string,sport int){
	var serverID =shost + "-" + strconv.Itoa(sport) + "-" + tag
	// 增加consul健康检查配置
	var check = consulapi.AgentServiceCheck{
		TCP:      shost + ":" + strconv.Itoa(sport),
        Interval: "10s",
		Timeout:  "5s",
		Notes:    "Consul check service health status.",
		DeregisterCriticalServiceAfter : "10s",
	}
	// 创建注册到consul的服务到
	var registration = &consulapi.AgentServiceRegistration{
		ID:serverID,
		Name:tag,
		Port:sport,
		Tags:[]string{tag},
		Address:shost,
		Check:&check,
	}

	// 注册服务到consul
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
        log.Fatal(err)
	}
}


func BuildByName(name string) *ServiceInfo {
	 var lastIndex uint64
	 services, metainfo, _ := client.Health().Service(name, "", true, &consulapi.QueryOptions{
        WaitIndex: lastIndex, // 同步点，这个调用将一直阻塞，直到有新的更新
	})
	lastIndex = metainfo.LastIndex
	var sers []ServiceInfo
    for _, service := range services {
		ser:=ServiceInfo{
			Host:service.Service.Address,
			Port:service.Service.Port,
		}
		sers = append(sers, ser)
	}
	if len(sers)!=0{
		return &sers[until.RangeRand(0,int64(len(sers)-1))]
	}
	return nil
}
func GetKv(key string) []byte{
	data, _ , _ :=client.KV().Get(key, nil)
	if data == nil {
        return []byte{}
    }
	return data.Value
}

